import { Select,Icon,Button } from "antd";
import React from "react";
import styles from "../../index.less"
import { getUuid } from "@/utils/utils";
import Sortable from 'sortablejs';
import {arrayMoveImmutable} from 'array-move';
import { formFieldList } from "@/services/formInteraction";
import { fetchApiListById } from "@/services/basiccapacity";

class ReportSetting extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      optionContentList:[
        {
          type:"",
          apiId:"",
          fieldId:""
        }
      ],
      fieldList:[],
      apiList:[],
      domKey:getUuid()
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
    this.drawDragBox()
  }

  initForm = data => {
    this.getFieldList()
    this.getApiList()
    this.setState({
      optionContentList:data
    })
  }

  getFieldList = async () => {
    const { formId } = this.props;
    const res = await formFieldList({formId})
    this.setState({
      fieldList:res
    })
  }

  getApiList = async () => {
    const res = await fetchApiListById({current:1,size:9999999999999999,type:1})
    this.setState({
      apiList:res.records
    })
  }

  changeOptionContent = (value,index,type) => {
    const list = JSON.parse(JSON.stringify(this.state.optionContentList))
    list[index][type] = value;
    if(type != 'fieldId'){
      list[index].fieldId = ''
    }
    this.setState({
      optionContentList:JSON.parse(JSON.stringify(list))
    })
  }

  removeOptionContent = index => {
    const list = JSON.parse(JSON.stringify(this.state.optionContentList))
    const newList = []
    for(const i in list){
      if(i!= index){
        newList.push(list[i])
      }
    }
    this.setState({
      optionContentList:newList
    })
  }

  drawDragBox = () => {
    const that = this;
    const el = document.getElementById('optionContent')
    new Sortable(el, {
      group: {
        name:"optionContent",
        pull:false,
        put:true
      },
      handle:".anticon-unordered-list",
      animation: 150,
      // 结束拖拽
      onEnd: function (/**Event*/evt) {
        const list = JSON.parse(JSON.stringify(that.state.optionContentList))
        const newArray = arrayMoveImmutable(list, evt.oldIndex, evt.newIndex);
        that.setState({
          optionContentList:newArray,
          domKey:getUuid()
        },() => {
          that.drawDragBox()
        })
      },
    });
  }

  addOptionContent = () => {
    const list = JSON.parse(JSON.stringify(this.state.optionContentList))
    list.push({
      type:"",
      apiId:"",
      fieldId:""
    })
    this.setState({
      optionContentList:list,
    })
  }

  checkSave = () => {
    const { optionContentList } = this.state;
    this.props.doSaveReport(optionContentList)
  }

  renderResponseField = apiId => {
    const { apiList } = this.state;
    let responseList = []
    for(const a of apiList){
      if(a.id == apiId){
        responseList = a.fieldList ? a.fieldList.filter(f => f.type == 2) : []
      }
    }
    
    return responseList.map(r => {
      return <Select.Option value={r.id} key={r.id}>{r.nameZh}</Select.Option>
    })
  }

  render(){
    const { optionContentList,fieldList,apiList,domKey } = this.state;

    return(
      <div>
        <div id='optionContent' key={domKey}>
          {
            optionContentList.map((item,index) => {
              return (
                <div key={index} className={styles.optionBox} style={{marginBottom:10}}>
                  <Icon type='unordered-list' className={styles.dragIcon} />
                  <label>{index + 1}、</label>
                  <Select style={{width:100,marginRight:10}} value={item.type} onChange={value => this.changeOptionContent(value,index,'type')}>
                    <Select.Option value={0}>表单字段</Select.Option>
                    <Select.Option value={1}>接口字段</Select.Option>
                  </Select>
                  {
                    item.type == 0 ? (
                      <Select onChange={(value) => this.changeOptionContent(value,index,'fieldId')} style={{width:300}} value={item.fieldId}>
                        {
                          fieldList.map(f => {
                            return <Select.Option key={f.id} value={f.id}>{f.name}</Select.Option>
                          })
                        }
                      </Select>
                    ) : (
                      <Select onChange={(value) => this.changeOptionContent(value,index,'apiId')} style={{width:300}} value={item.apiId}>
                        {
                          apiList.map(f => {
                            return <Select.Option key={f.id} value={f.id}>{f.name}</Select.Option>
                          })
                        }
                      </Select>
                    )
                  }
                  {
                    item.type == 1 ? (
                      <Select style={{width:200,marginLeft:10}} value={item.fieldId} onChange={(value) => this.changeOptionContent(value,index,'fieldId')}>
                        {
                          this.renderResponseField(item.apiId)
                        }
                      </Select>
                    ) : ''
                  }
                  
                  <Icon type='delete' className={styles.removeIcon} onClick={() => this.removeOptionContent(index)} />
                </div>
              )
            })
          }
        </div>
        <Button type='link' icon='plus' style={{marginTop:10}} onClick={this.addOptionContent}>新增报表字段</Button>
        <div style={{marginTop:24}}>
          <Button type="primary" onClick={this.checkSave}>保存</Button>
        </div>
      </div>
    )
  }
}

export default ReportSetting